#include "udp_echo_server.h"
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <strings.h>
#include <stdio.h>
#include "socket_tool.h"
#include <string.h>

void start_udp_echo_server()
{

    puts("启动udp echo server");

    struct sockaddr_in server_ip;
    bzero(&server_ip, sizeof(server_ip));
    server_ip.sin_family = AF_INET;
    server_ip.sin_addr.s_addr = htonl(INADDR_ANY);
    server_ip.sin_port = htons(12346);

    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    bind(sockfd, &server_ip, sizeof(server_ip));

    do_echo(sockfd);

}

void do_echo(int sockfd)
{

    size_t BUF_SIZE = 256;
    char buf[BUF_SIZE];
    bzero(buf, sizeof(buf));

    struct sockaddr_in client_addr;
    socklen_t client_len = (socklen_t) sizeof(client_addr);

    for ( ; ; ) 
    {
        int read_bytes = recvfrom(sockfd, buf, BUF_SIZE, 0, &client_addr, &client_len);
        if (read_bytes < 0) {
            puts("未读取到数据");
            continue;
        }

        char *client = sockaddr_to_string(&client_addr);
        printf("收到客户消息，client=%s，消息为：%s", client, buf);
        free(client);

        // 回射
        sendto(sockfd, buf, strlen(buf) + 1, 0, &client_addr, client_len);
    }
    
}
